package com.sky.controller.admin;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;

/**
 * @author 陈俊宇
 * * @date 2025/9/17
 */
@RestController()
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {



    // 允许上传的文件类型
    private static final String[] ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".xls", ".xlsx", ".csv"};
    // 文件保存的基础路径
    private static final String BASE_DIR = "E:/image/";
    // 最大文件大小 10MB
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> upload(@RequestParam("file") MultipartFile multipartFile) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 检查文件是否为空
            if (multipartFile.isEmpty()) {
                result.put("success", false);
                result.put("message", "上传文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 2. 检查文件大小
            if (multipartFile.getSize() > MAX_FILE_SIZE) {
                result.put("success", false);
                result.put("message", "文件大小不能超过10MB");
                return ResponseEntity.badRequest().body(result);
            }

            // 3. 获取原始文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String fileExtension = "";

            // 4. 检查文件扩展名
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                boolean allowed = false;
                for (String ext : ALLOWED_EXTENSIONS) {
                    if (ext.equalsIgnoreCase(fileExtension)) {
                        allowed = true;
                        break;
                    }
                }
                if (!allowed) {
                    result.put("success", false);
                    result.put("message", "不支持的文件类型");
                    return ResponseEntity.badRequest().body(result);
                }
            } else {
                result.put("success", false);
                result.put("message", "文件缺少扩展名");
                return ResponseEntity.badRequest().body(result);
            }

            // 5. 生成唯一文件名（避免重名）
            String newFilename = generateUniqueFilename(originalFilename);

            // 6. 创建保存目录（按日期分类）
            String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File dir = new File(BASE_DIR + datePath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 7. 保存文件
            File dest = new File(dir, newFilename);
            multipartFile.transferTo(dest);

            // 8. 返回成功信息
            result.put("success", true);
            result.put("message", "文件上传成功");
            result.put("filePath", datePath + "/" + newFilename);
            result.put("originalName", originalFilename);
            result.put("fileSize", multipartFile.getSize());

            log.info("文件上传成功：{} -> {}", originalFilename, dest.getAbsolutePath());

            return ResponseEntity.ok(result);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            result.put("success", false);
            result.put("message", "文件上传失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 生成唯一文件名
     * @param originalFilename 原始文件名
     * @return 新文件名（UUID + 原始扩展名）
     */
    private String generateUniqueFilename(String originalFilename) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return uuid + extension;
    }

}
